#include "attributewidget.h"
#include <QLabel>
#include <QPainter>
#include <QHeaderView>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QListWidgetItem>
#include <QHBoxLayout>
#include <QScrollBar>
#include <QFontDialog>
#include <QColorDialog>
#include <QLineEdit>
#include <QAction>
#include <QCheckBox>
#include <setformatdlg.h>
#include "nofocusdelegate.h"
#include "mylineedit.h"
#include "setresourcesdlg.h"
#include "stylesetwidget.h"

QString str_properties = "";


AttributeWidget::AttributeWidget(QScrollArea *parent)
    : QScrollArea(parent)
{
    setWindowFlags(Qt::FramelessWindowHint);

//    setMaximumSize((Screen::GetScreenWidth())>>1, (Screen::GetScreenHeight()));
//    setMinimumSize((Screen::GetScreenWidth())>>5, (Screen::GetScreenHeight())>>4);
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    setFrameShape(QScrollArea::NoFrame);
    setWidgetResizable(true);

#if 0
    table_attribute = new QTableWidget(this);
    table_attribute->setFrameShape(QTableWidget::NoFrame);
    table_attribute->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    table_attribute->horizontalHeader()->setSectionsClickable(false);
    table_attribute->horizontalHeader()->setStretchLastSection(true);

    table_attribute->setItemDelegate(new NoFocusDelegate());

    QStringList headerText;
    headerText<<QObject::tr("attribute")<<QObject::tr("value");  //表头标题用QStringList来表示
    table_attribute->setColumnCount(headerText.count());
    table_attribute->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
    table_attribute->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
    table_attribute->horizontalHeader()->setStyleSheet("QHeaderView::section{border:1px solid gray};");
    table_attribute->setColumnWidth(0, 120);
    table_attribute->setHorizontalHeaderLabels(headerText);
    table_attribute->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    table_attribute->setShowGrid(false);
    table_attribute->setStyleSheet("QTableWidget::Item{border:0px solid gray; border-bottom:1px solid lightgray;}"
                              "QTableWidget::Item::selected{background-color:skyblue};");

    table_attribute->verticalHeader()->hide();

    table_attribute->horizontalScrollBar()->hide();

    setWidget(table_attribute);
#else
    list_attribute = new QListWidget(this);
    list_attribute->setFrameShape(QListWidget::NoFrame);
    list_attribute->setViewMode(QListView::ListMode);
    list_attribute->setResizeMode(QListView::Adjust);
    list_attribute->setFocusPolicy(Qt::NoFocus);
    list_attribute->setItemDelegate(new NoFocusDelegate());
    list_attribute->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(list_attribute);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSizeConstraint(QLayout::SetMinAndMaxSize);
    setLayout(layout);
#endif

    for (int i = 0; i < attribute_num; i++)
    {
        attribute_item[i].used = false;
        attribute_item[i].item = new QListWidgetItem(list_attribute);
        attribute_item[i].item_widget = new AttributeEdit(list_attribute);
        list_attribute->setItemWidget(attribute_item[i].item, attribute_item[i].item_widget);
        attribute_item[i].item->setSizeHint(QSize(Screen::GetScreenWidth()>>5, 30));
        attribute_item[i].item->setHidden(true);
        connect(attribute_item[i].item_widget, &AttributeEdit::editingFinished, this, &AttributeWidget::itemChanged);
    }

    AddStyleWidget();
}

AttributeWidget::~AttributeWidget()
{
    if (style_widget != NULL)
    {
        delete style_widget;
        style_widget = NULL;
    }
}

void AttributeWidget::itemChanged(QString value)
{
    QString object_name = sender()->objectName();
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base[object_name.toStdString()] = value.toStdString();
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);

    m_viewobjectinfo->object->Update(os.str());
}

void AttributeWidget::ParseAttribute(std::string jsonStr, bool exist)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value value;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &value, &errs);

    if (!res || !errs.empty())
    {
         LOG_QDEBUG << "json parse faild" << QString::fromStdString(errs);
    }

    {
        if (CheckJsonValueType(value, "zindex", Json::stringValue))
        {
            generate_item("zindex", QString::fromStdString(value["zindex"].asString()));
        }

        if (CheckJsonValueType(value, "stid", Json::stringValue))
        {
            generate_item("stid", QString::fromStdString(value["stid"].asString()));
        }

        if (CheckJsonValueType(value, "idtype", Json::stringValue))
        {
            generate_item("idtype", QString::fromStdString(value["idtype"].asString()));
        }

        if (CheckJsonValueType(value, "x", Json::stringValue) &&
                CheckJsonValueType(value, "y", Json::stringValue) &&
                CheckJsonValueType(value, "w", Json::stringValue) &&
                CheckJsonValueType(value, "h", Json::stringValue))
        {
            QString x = QString::fromStdString(value["x"].asString());
            QString y = QString::fromStdString(value["y"].asString());
            QString w = QString::fromStdString(value["w"].asString());
            QString h = QString::fromStdString(value["h"].asString());
            generate_item("x", x);
            generate_item("y", y);
            generate_item("w", w);
            generate_item("h", h);
        }

        if (CheckJsonValueType(value, "name", Json::stringValue))
        {
            QString aaa = QString::fromStdString(value["name"].asString());
            generate_item("name", QString::fromStdString(value["name"].asString()));
        }

        if (CheckJsonValueType(value, "content", Json::stringValue))
        {
            generate_item("content", QString::fromStdString(value["content"].asString()));
        }

        if (CheckJsonValueType(value, "style", Json::stringValue))
        {
            generate_item("style", QString::fromStdString(value["style"].asString()));
        }

        if (CheckJsonValueType(value, "normal", Json::stringValue))
        {
           generate_item("normal", QString::fromStdString(value["normal"].asString()));
        }
        if (CheckJsonValueType(value, "one_left", Json::stringValue))
        {
           generate_item("one_left", QString::fromStdString(value["one_left"].asString()));
        }
        if (CheckJsonValueType(value, "one_right", Json::stringValue))
        {
           generate_item("one_right", QString::fromStdString(value["one_right"].asString()));
        }
        if (CheckJsonValueType(value, "two", Json::stringValue))
        {
           generate_item("two", QString::fromStdString(value["two"].asString()));
        }
        if (CheckJsonValueType(value, "three", Json::stringValue))
        {
           generate_item("three", QString::fromStdString(value["three"].asString()));
        }
        if (CheckJsonValueType(value, "four", Json::stringValue))
        {
           generate_item("four", QString::fromStdString(value["four"].asString()));
        }
        if (CheckJsonValueType(value, "five", Json::stringValue))
        {
           generate_item("five", QString::fromStdString(value["five"].asString()));
        }
        if(CheckJsonValueType(value, "six_left", Json::stringValue))
        {
           generate_item("six_left", QString::fromStdString(value["six_left"].asString()));
        }
        if (CheckJsonValueType(value, "six_right", Json::stringValue))
        {
           generate_item("six_right", QString::fromStdString(value["six_right"].asString()));
        }
        if (CheckJsonValueType(value, "skip", Json::stringValue))
        {
            generate_item("skip", QString::fromStdString(value["skip"].asString()));
        }
        if (CheckJsonValueType(value, "offset_x", Json::stringValue))
        {
            generate_item("offset_x", QString::fromStdString(value["offset_x"].asString()));
        }
        if (CheckJsonValueType(value, "cross", Json::stringValue))
        {
            generate_item("cross", QString::fromStdString(value["cross"].asString()));
        }
        if (CheckJsonValueType(value, "future", Json::stringValue))
        {
            generate_item("future", QString::fromStdString(value["future"].asString()));
        }
        if (CheckJsonValueType(value, "pass", Json::stringValue))
        {
            generate_item("pass", QString::fromStdString(value["pass"].asString()));
        }

        if (CheckJsonValueType(value, "trainnum", Json::stringValue))
        {
            generate_item("trainnum", QString::fromStdString(value["trainnum"].asString()));
        }

        if (CheckJsonValueType(value, "dtime", Json::stringValue))
        {
            generate_item("dtime", QString::fromStdString(value["dtime"].asString()));
        }

        if (CheckJsonValueType(value, "stime", Json::stringValue))
        {
            generate_item("stime", QString::fromStdString(value["stime"].asString()));
        }

        if (CheckJsonValueType(value, "timeformat", Json::stringValue))
        {
            generate_item("timeformat", QString::fromStdString(value["timeformat"].asString()));
        }
        if (CheckJsonValueType(value, "time_ms", Json::stringValue))
        {
            generate_item("time_ms", QString::fromStdString(value["time_ms"].asString()));
        }
        if (CheckJsonValueType(value, "startIndex", Json::stringValue))
        {
            generate_item("startIndex", QString::fromStdString(value["startIndex"].asString()));
        }
        if (CheckJsonValueType(value, "endIndex", Json::stringValue))
        {
            generate_item("endIndex", QString::fromStdString(value["endIndex"].asString()));
        }
        if (CheckJsonValueType(value, "positioninfo", Json::stringValue))
        {
            generate_item("positioninfo", QString::fromStdString(value["positioninfo"].asString()));
        }
        if (CheckJsonValueType(value, "url", Json::stringValue))
        {
            generate_item("url", QString::fromStdString(value["url"].asString()));
        }

        if (CheckJsonValueType(value, "exitcfg", Json::stringValue))
        {
            generate_item("exitcfg", QString::fromStdString(value["exitcfg"].asString()));
        }

        if (CheckJsonValueType(value, "emergencyList", Json::stringValue))
        {
            generate_item("emergencyList", QString::fromStdString(value["emergencyList"].asString()));
        }

        if (CheckJsonValueType(value, "open", Json::stringValue))
        {
            generate_item("open", QString::fromStdString(value["open"].asString()));
        }

        if (CheckJsonValueType(value, "close", Json::stringValue))
        {
            generate_item("close", QString::fromStdString(value["close"].asString()));
        }

        if (CheckJsonValueType(value, "isolation", Json::stringValue))
        {
            generate_item("isolation", QString::fromStdString(value["isolation"].asString()));
        }

        if (CheckJsonValueType(value, "fault", Json::stringValue))
        {
            generate_item("fault", QString::fromStdString(value["fault"].asString()));
        }

        if (CheckJsonValueType(value, "obstacle", Json::stringValue))
        {
            generate_item("obstacle", QString::fromStdString(value["obstacle"].asString()));
        }

        if (CheckJsonValueType(value, "steptime", Json::stringValue))
        {
            generate_item("steptime", QString::fromStdString(value["steptime"].asString()));
        }

        if (CheckJsonValueType(value, "stepwidth", Json::stringValue))
        {
            generate_item("stepwidth", QString::fromStdString(value["stepwidth"].asString()));
        }
        if (CheckJsonValueType(value, "id", Json::stringValue))
        {
            generate_item("id", QString::fromStdString(value["id"].asString()));
        }
        if (CheckJsonValueType(value, "next", Json::stringValue))
        {
            generate_item("next", QString::fromStdString(value["next"].asString()));
        }
        if (CheckJsonValueType(value, "arrive", Json::stringValue))
        {
            generate_item("arrive", QString::fromStdString(value["arrive"].asString()));
        }
        if (CheckJsonValueType(value, "start", Json::stringValue))
        {
            generate_item("start", QString::fromStdString(value["start"].asString()));
        }
    }

}

void AttributeWidget::generate_item(QString attribute, QString value)
{
    if (attribute == "")
        return;

    for (int i = 0; i < list_attribute->count() - 1; i++)
    {
        QListWidgetItem *item = list_attribute->item(i);
        if (item->isHidden())
        {
            item->setHidden(false);
            AttributeEdit *edit = static_cast<AttributeEdit *>(list_attribute->itemWidget(item));
            if (edit)
            {
                edit->setObjectName(attribute);
                edit->setKey(attribute);
                edit->setValue(value);
            }
            break;
        }
    }
}

void AttributeWidget::cancel_attribute()
{
    for (int i = 0; i < list_attribute->count(); i++)
    {
        list_attribute->item(i)->setHidden(true);
    }
}

void AttributeWidget::AddStyleWidget()
{    
    style_item = new QListWidgetItem(list_attribute);

    style_widget = new StyleSetWidget;
    style_widget->setStyleSheet("QTreeWidget {border:none;}"
                                "QTreeWidget::Item {height:30px; border:0px solid gray; border-bottom:0px solid gray;}"
                                "QTreeWidget::Item:hover {background:skyblue;}");
    list_attribute->setItemWidget(style_item, style_widget);
    style_item->setHidden(true);
}

void AttributeWidget::slt_show_attribute(QString id, ViewObjectInfo* info)
{
    m_id = id;
    m_viewobjectinfo = info;
    cancel_attribute();
    info->object->GetAttribute(info->attribute);
    ParseAttribute(info->attribute, false);

    style_item->setHidden(false);

    style_widget->StyleWidgetSetData(info);
}

void AttributeWidget::slt_update_attribute(QString id, ViewObjectInfo* info)
{
    slt_show_attribute(id, info);
}

void AttributeWidget::delete_attribute(QString id)
{
    Q_UNUSED(id);
    m_id = "";
    m_viewobjectinfo = NULL;

    style_widget->DeleteStyleGroup();

    cancel_attribute();
}

